#!/usr/bin/python

"""
Time Chess Engine Communication Protocol Interface

A program to use the TimeChessEngine to communicate with a GUI using the Time Chess Engine Communication Protocol, which I just made up, based on the Chess Engine Communication Protocol
"""

from TimeChessEngine import TimeChessEngine
from TimeChessUtil import *
import sys, re
import json

class TCECPInterface(object):
	def __init__(self):
		self.engine = TimeChessEngine()

	def out(self,outstr):
		sys.stdout.write(outstr+"\n")
		sys.stdout.flush()

	def mainLoop(self):
		done = False
		while not done:
			try:
				instr = raw_input()
				if instr.strip() == "quit":
					sys.stderr.write("TCECPInterface: Got 'quit', exiting.")
					sys.stderr.flush()
					done = True
				else:
					self.parseInput(instr)
			except EOFError:
				pass
	
	def parseInput(self, instr):
		inarr = instr.split()
		if   (instr == "new"):
			self.engine = TimeChessEngine()

		elif (inarr[0] == "ping"):
			self.out("pong %s"%inarr[1])

		elif (re.match(r"^[a-h]\dt\d+[a-h]\dt\d+$", instr)):
			positions = re.findall(r"[a-h]\dt\d+", instr)
			result = self.engine.attemptMove(Move(Pos(positions[0]), Pos(positions[1])))
			if result:
				self.out(result.message)
			else:
				self.out("Illegal move (%s): %s" % (result.message, instr))

		elif (re.match(r"[a-h]\dt\d+", instr)):
			moves = self.engine.getPossibleMoves(Pos(instr))
			self.out("moves (%s): %s" %
						(instr, json.dumps([str(m.end) for m in moves])))

		elif (inarr[0] == "getState"):
			if (len(inarr) >= 2):
				if inarr[1].strip() == "t":
					self.out("%s"%self.engine.t)
				elif inarr[1].strip() == "futureQueue":
					futureQueue = [(str(p.pos), p.color, p.char) for p in self.engine.futureQueue]
					outstr = "futureQueue: %s" % json.dumps(futureQueue)
					self.out(outstr)
				else:
					turn = int(inarr[1])
					board = self.engine.game.getBoardAtTurn(turn)
					data=[(str(p.pos), p.color, p.char) for p in board.flatten() if p]
					self.out("state (%s): %s"%(turn,json.dumps(data)))





if __name__ == "__main__":
	i = TCECPInterface()
	i.mainLoop()
	
